package vip.pwztx.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.jsoup.Jsoup;
import org.jsoup.nodes.DataNode;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Service;
import vip.pwztx.service.CloudApiService;

import java.util.HashMap;
import java.util.List;

/**
 * 云盘接口Service实现类
 *
 * @author zhoubaohua
 * @date 2020/8/28
 */
@Service
public class CloudApiServiceImpl implements CloudApiService {

    @Override
    public String getLanZouYunDownloadUrl(String url, String password) throws Exception {
        Document document = Jsoup.connect(url)
                .userAgent("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36")
                .timeout(5000)
                .get();
        Elements elements = document.getElementsByTag("script");
        List<DataNode> lineText = elements.dataNodes();
        String sign = lineText.get(0).toString().split("action=downprocess&sign=")[1].split("&p='\\+pwd,")[0];
        HttpRequest request = HttpUtil.createPost("https://" + url.split("/")[2].trim() + "/ajaxm.php");
        HttpResponse response = request.addHeaders(new HashMap<String, String>(4) {{
            put("Content-Type", "application/x-www-form-urlencoded");
            put("Referer", url);
            put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36");
        }}).form(new HashMap<String, Object>(4) {{
            put("action", "downprocess");
            put("sign", sign);
            put("p", password);
        }}).execute();
        String json = response.body();
        JSONObject jsonObject = JSONUtil.parseObj(json);
        return jsonObject.getStr("dom") + "/file/" + jsonObject.getStr("url");
    }
}
